package com.bparser.parser;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Concrete class for parsing branches table from kkb.kz/BranchesOp
 * 
 * @author murakami
 * 
 */

public class ParserExecutor {
	private final String TAG = getClass().getSimpleName();
	private static Map<String, Integer> cities;
	private static final String URL = "http://ru.kkb.kz/page/BranchesOp";
//	private static final String ATMS_URL = "http://ru.kkb.kz/page/BranchesOp";

	private Parser parser;
	private URL url;
	private HttpURLConnection con;

	public interface ParserCallback {
		void postOperation();

		void onOperationFail();
	}

	public ParserExecutor() {
		
	}
	
	public ParserExecutor(Parser parser) {
		this.parser = parser;
	}

	public void initCities() throws Exception {
		if(parser == null)
			throw new NullPointerException("Please assign a parser");
		cities = new HashMap<String, Integer>();
		url = new URL(URL);
		con = (HttpURLConnection) url.openConnection();

		String htmlSource = Utils.getStringFromStream(con.getInputStream());
		Elements citiesSource = Utils.getAllElementFromString(htmlSource,
				"select[name=city] > option");
		for (Element city : citiesSource) {
			cities.put(city.text(), Integer.valueOf(city.attr("value")));
		}
	}

	public void execute() {
		if (cities == null) {
			throw new NullPointerException("Cities is not initialized");
		}

		for (int city : cities.values()) {
			try {
				url = new URL(parser.getURL() + "?city=" + city);
				con = (HttpURLConnection) url.openConnection();

				String htmlSource = Utils.getStringFromStream(con
						.getInputStream());

				for (Map.Entry<String, Integer> entry : cities.entrySet()) {
					if (entry.getValue() == city)
						System.out.println("City: " + entry.getKey());
				}

				parser.execute(htmlSource);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void setParser(Parser parser) {
		this.parser = parser;
	}
}